﻿namespace TamTam.SharePoint2010.Social {

    #region [ Usings ]

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using Microsoft.SharePoint;
    using Microsoft.Office.Server.UserProfiles;
    using Microsoft.Office.Server.ActivityFeed;

    #endregion

    /// <summary>
    /// Wrapper to the Status list of social updates.
    /// </summary>
    public class SocialUpdateStatusList {

        internal const string ListName = "SocialProfileUpdates";
        
        /// <summary>
        /// Get the Status list
        /// </summary>
        /// <param name="site">Site context</param>
        /// <returns>Created or found Status list</returns>
        public static SPList GetList(SPSite site) {

            SPList socialProfileUpdates = null;
            try {
                socialProfileUpdates = site.RootWeb.Lists[SocialUpdateStatusList.ListName];
            }
            catch (Exception ec) {
            }
            // it does not exists, we will create it then.
            if (socialProfileUpdates == null) {
                using (SPSite elevsite = new SPSite(site.ID)) {

                    elevsite.AllowUnsafeUpdates = true;
                    elevsite.RootWeb.AllowUnsafeUpdates = true;

                    elevsite.RootWeb.Lists.Add(
                        SocialUpdateStatusList.ListName, 
                        "Status of SocialProfileUpdates", 
                        SPListTemplateType.GenericList);

                    elevsite.RootWeb.Update();

                    elevsite.AllowUnsafeUpdates = true;
                    elevsite.RootWeb.AllowUnsafeUpdates = true;

                    socialProfileUpdates = elevsite.RootWeb.Lists[SocialUpdateStatusList.ListName];

                    // add / rename fields
                    socialProfileUpdates.Fields[SPBuiltInFieldId.Title].Title = "UserProfile";
                    socialProfileUpdates.Fields[SPBuiltInFieldId.Title].Update();

                    socialProfileUpdates.Fields.Add("ActivityType", SPFieldType.Text, true);
                    socialProfileUpdates.Fields.Add("LastFeedItemID", SPFieldType.Text, true);
                    
                    socialProfileUpdates.NoCrawl = true;
                    socialProfileUpdates.OnQuickLaunch = false;

                    socialProfileUpdates.Update();
                }

                try {
                    site.RootWeb.Update();
                    socialProfileUpdates = site.RootWeb.Lists[SocialUpdateStatusList.ListName];
                }
                catch (Exception exc) {
                }
            }
            return socialProfileUpdates;
        }

        public static string GetLastItemId(SPSite site, ActivityType activitytype, UserProfile user) {
            SPList socialProfileUpdates = GetList(site);

            string result = null;

            SPQuery q = new SPQuery();
            q.Query = string.Format(
                "<Where><And><Eq><FieldRef Name=\"Title\" /><Value Type=\"Text\">{0}</Value></Eq><Eq><FieldRef Name=\"ActivityType\" /><Value Type=\"Text\">{1}</Value></Eq></And></Where>",
                user["AccountName"].Value,
                activitytype.ActivityTypeName);
            SPListItemCollection items = socialProfileUpdates.GetItems(q);
            if (items.Count > 0) {
                SPListItem item = items[0];
                result = item["LastFeedItemID"] as string;
            }

            return result;
        }

        public static DateTime GetLastItemDateTime(SPSite site, ActivityType activitytype, UserProfile user) {
            DateTime result = DateTime.MinValue;

            SPList socialProfileUpdates = GetList(site);
            if (socialProfileUpdates != null) {

                // query the list for this activitytype and user
                SPQuery q = new SPQuery();
                q.Query = string.Format(
                    "<Where><And><Eq><FieldRef Name=\"Title\" /><Value Type=\"Text\">{0}</Value></Eq><Eq><FieldRef Name=\"ActivityType\" /><Value Type=\"Text\">{1}</Value></Eq></And></Where>",
                    user["AccountName"].Value,
                    activitytype.ActivityTypeName);

                SPListItemCollection items = socialProfileUpdates.GetItems(q);
                if (items.Count > 0) {
                    // we found a match, get the created date for this listitem.
                    SPListItem item = items[0];
                    try {
                        if (item[SPBuiltInFieldId.Created] != null)
                            result = (DateTime)item[SPBuiltInFieldId.Created];
                    }
                    catch (Exception exc) {
                        // this should not happen?
                    }
                }
            }
            return result;
        }
        
        public static void SetLastItemId(SPSite site, ActivityType activitytype, UserProfile user, string lastItemId) {

            RemoveLastItemId(site, activitytype, user);
            
            SPList socialProfileUpdates = GetList(site);
            if (socialProfileUpdates != null) {
                SPListItem item = socialProfileUpdates.AddItem();
                item["UserProfile"] = user["AccountName"].Value as string;
                item["ActivityType"] = activitytype.ActivityTypeName;
                item["LastFeedItemID"] = lastItemId;
                item.Update();
            }
        }

        public static void RemoveLastItemId(SPSite site, ActivityType activitytype, UserProfile user) {
            SPList socialProfileUpdates = GetList(site);

            if (socialProfileUpdates != null) {
                SPQuery q = new SPQuery();
                q.Query = string.Format(
                    "<Where><And><Eq><FieldRef Name=\"Title\" /><Value Type=\"Text\">{0}</Value></Eq><Eq><FieldRef Name=\"ActivityType\" /><Value Type=\"Text\">{1}</Value></Eq></And></Where>",
                    user["AccountName"].Value,
                    activitytype.ActivityTypeName);

                SPListItemCollection items = socialProfileUpdates.GetItems(q);
                foreach (SPListItem item in items) {
                    // delete the found item
                    socialProfileUpdates.Items.DeleteItemById(item.ID);
                }
            }
        }
    }
}